<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<title>图片交互</title>
		{% load static %}
		<link href="{% static 'css/style.css' %}" rel="stylesheet">
		<link href="{% static 'plugins/bootstrap-5.3.0/css/bootstrap.min.css' %}" rel="stylesheet">
		<link href="{% static 'css/training.css' %}" rel="stylesheet">
<style>
.custom-file-upload {
margin: 5px 0;
border: 1px dashed #ccc;
border-radius: 4px;
padding: 3px;
background-color: white;
cursor: pointer;
transition: all 0.3s ease;
text-align: center;
}

.custom-file-upload:hover {
border-color: #007bff;
background-color: #f8f9fa;
}

.custom-file-upload i {
font-size: 24px;
margin-right: 1px;
}

.upload-container {
transition: all 0.3s ease;
}

.feedback-message {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 10000;
display: none;
align-items: center;
padding: 10px 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
animation: fadeInOut 4s ease-in-out forwards;
}

.feedback-message.success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}

.feedback-message.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}

.feedback-icon {
margin-right: 8px;
}

@keyframes fadeInOut {
0% {
opacity: 0;
top: 0;
}
10% {
opacity: 1;
top: 20px;
}
90% {
opacity: 1;
top: 20px;
}
100% {
opacity: 0;
top: 0;
}
}

/* 确保文件详情区域始终显示 */
.file-details {
margin-top: 5px;
}

/* 文件名和大小样式 */
.file-info-label {
font-weight: bold;
color: #666;
}

.file-info-value {
font-weight: bold;
color: #333;
}

/* 引导内容框滚动条样式 */
#resultPanelBody::-webkit-scrollbar {
  width: 8px;
}

#resultPanelBody::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

#resultPanelBody::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

#resultPanelBody::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

#resultPanelBody img {
	cursor: pointer;
	transition: transform 0.2s;
}
#resultPanelBody img:hover {
	transform: scale(1.02);
	box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

/* 确保图片和文字在滚动容器中正确显示 */
.image-result-container {
  margin-bottom: 15px;
}

.generated-image {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  max-width: 100%;
  max-height: 300px;
}

/* 添加结果列表样式 */
.results-container {
margin-top: 20px;
padding: 20px;
max-height: 400px; /* 限制高度，超出后自动出现滚动条 */
overflow-y: auto; /* 垂直方向滚动 */
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 历史记录表格强制对齐 */
.results-table {
width: 97%;
table-layout: fixed;
border-collapse: collapse;
background-color: white;
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
overflow: hidden
}

.results-table th,
.results-table td {
padding: 12px 15px;
border-bottom: 1px solid #dee2e6;
word-wrap: break-word;
text-align: center;
vertical-align: middle;
}

/* 调整列宽：让前几列变窄，输出图片列变宽 */
.results-table th:nth-child(1),
.results-table td:nth-child(1) {
width: 12%; /* 时间列 */
}

.results-table th:nth-child(2),
.results-table td:nth-child(2) {
width: 15%; /* 事件列 - 变窄 */
text-align: left;
}

.results-table th:nth-child(3),
.results-table td:nth-child(3) {
width: 15%; /* 引导方向列 - 变窄 */
text-align: left;
}

.results-table th:nth-child(4),
.results-table td:nth-child(4) {
width: 18%; /* 用户观点列 - 变窄 */
text-align: left;
}

.results-table th:nth-child(5),
.results-table td:nth-child(5) {
width: 40%; /* 输出图片列 - 变宽 */
}

.module-header {
background-color: #337ab7;
color: white;
padding: 12px 15px;
margin: 0; /* 清除 margin */
border-radius: 10px 10px 0 0;
text-align: center;
font-weight: bold;
width: 100%; /* 宽度100% */
box-sizing: border-box; /* 确保 padding 不影响宽度 */
}

/* 调整模块的 padding，避免标题覆盖内容 */
.module {
padding: 0; /* 清除模块的内边距 */
padding-top: 20px; /* 只保留上内边距，给标题留空间 */
width: 26%;
background-color: #f9f9f9;
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
text-align: center;
}
.module-container {
display: flex;
justify-content: center;
position: relative; /* 保持relative定位 */
top: 0;
left: 0;
transform: none;
width: 100%;
max-width: 1400px;
gap: 5%;
margin: 10px auto;
padding-top: 0; /* 确保无额外上内边距 */
}
.current-result-content p {
margin: 15px 0;
text-align: left;
padding-left: 20%;
}

.emotion-result {
font-size: 18px;
font-weight: bold;
}

.emotion-positive {
color: #28a745;
}

.emotion-negative {
color: #dc3545;
}

.emotion-neutral {
color: #ffc107;
}

.progress-container {
margin-top: 15px;
display: none;
}

.progress {
height: 20px;
margin-bottom: 10px;
border-radius: 10px;
background-color: #f5f5f5;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}

.progress-bar {
height: 100%;
border-radius: 10px;
background-color: #337ab7;
width: 0%;
transition: width 0.3s ease;
text-align: center;
line-height: 20px;
color: white;
}

.progress-text {
font-size: 12px;
color: #666;
text-align: center;
}

.upload-btn {
background-color: #337ab7;
color: white;
border: none;
padding: 8px 16px;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
min-width: 100px;
}

.upload-btn:hover {
background-color: #286090;
}

.upload-btn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}

.upload-btn.uploading {
background-color: #f0ad4e;
}

.function_link {
text-decoration: none;
color: inherit;
font-size: 18px;
margin-left: 8px;
}

/* 新增样例视频模块样式 */
/*.sample-videos-container {*/
/*    width: 90%;*/
/*    max-width: 1400px;*/
/*    margin: 250px auto 30px;*/
/*    padding: 20px;*/
/*    background-color: #f9f9f9;*/
/*    border-radius: 10px;*/
/*    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);*/
/*    text-align: center;*/
/*}*/
.sample-videos-container {
width: 90%;
max-width: 1400px;
margin: 40px auto 30px;  /* 减少上边距，因为模块容器不再是绝对定位 */
padding: 20px;
background-color: #f9f9f9;
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
text-align: center;
}

.sample-videos-header {
background-color: #337ab7;
color: white;
padding: 10px 15px;
margin: -20px -20px 20px -20px;
border-radius: 10px 10px 0 0;
text-align: center;
font-weight: bold;
}

.sample-videos-grid {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
gap: 20px;
margin-top: 20px;
}

.sample-video-item {
width: 30%;
min-width: 250px;
background-color: white;
border-radius: 8px;
padding: 15px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}

.sample-video-item:hover {
transform: translateY(-5px);
}

.sample-video-wrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 比例 */
height: 0;
overflow: hidden;
margin-bottom: 10px;
border-radius: 5px;
background-color: #000;
}

.sample-video-wrapper video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
}

.sample-video-info {
text-align: left;
margin-top: 10px;
}

.sample-video-info p {
margin: 5px 0;
font-size: 14px;
}

.video-info-label {
font-weight: bold;
color: #666;
}

.video-info-value {
font-weight: bold;
color: #333;
}
/* 若只想让主内容区域滚动（可选），可保留下面这段 */
.main_content {
overflow-y: auto;
min-height: 90vh;     /* 保证至少一屏高 */
}

.home-link {
  text-decoration: none; /* 去除下划线 */
  color: white; /* 继承按钮文字颜色 */
  display: inline-block; /* 确保点击区域与按钮一致 */
}

/* 按钮样式调整 */
.home-btn {
  padding: 15px !important; /* 确保内边距生效 */
  font-size: 25px !important; /* 确保字体大小生效 */
  background-color: #156bb7;
  border-radius: 4px; /* 统一圆角 */
  transition: all 0.2s ease; /* 平滑过渡效果 */
  border: none; /* 去除边框 */
  cursor: pointer; /* 鼠标指针样式 */
}

/* 悬停效果 */
.home-btn:hover {
  opacity: 0.9; /* 轻微透明效果 */
  transform: translateY(-2px); /* 轻微上浮 */
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3); /* 增强阴影 */
}

/* 点击效果 */
.home-btn:active {
  transform: translateY(0); /* 恢复位置 */
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2); /* 减弱阴影 */
}

/* 确保按钮在各种状态下样式一致 */
.home-link:visited .home-btn {
  color: #fff; /* 访问后保持白色文字 */
}

/* 新增图片结果容器样式 */
    .image-result-container {
        margin-top: 20px;
        text-align: center;
    }
    .generated-image {
        max-width: 100%;
        max-height: 400px;
        border-radius: 8px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        margin: 10px 0;
    }
    .image-placeholder {
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
        border-radius: 8px;
        margin: 20px 0;
    }
    .sample-image-preview {
        width: 50%;
        height: 60px;
        object-fit: cover;
        border-radius: 4px;
        margin-bottom: 5px;
    }

</style>
	</head>
	<body>
		<!-- 导航栏（Bootstrap 5 写法） -->
		<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
			<div class="container-fluid">
				<a class="navbar-brand d-flex align-items-center" href="#">
					<!-- <img src="{% static 'images/logo.png' %}" alt="Logo" class="nav-logo me-2"> -->
					<div class="nav-title">情感分析与智能引导</div>
				</a>

				<div class="user-actions">
				<!-- <el-button type="primary" class="login-btn">登录</el-button> -->
				<a href="http://10.68.100.169:25001" class="home-link">
					<el-button type="primary" class="register-btn home-btn" style="padding: 25px;font-size: 25px;">回到首页</el-button>
				</a>
				</div>
			</div>
		</nav>

		<!-- 侧边栏（保持不变） -->
		<div class="sidebar-container">
			<div class="sidebar" style="margin-top: 45px;">
				<h2 class="sidebar-title">功能模块</h2>
				<ul class="nav-list">
					<li class="nav-item" style="margin-left:20px;">
						<a href="/emotion/upload" class="active function_link" style="font-size: 25px;">情感分析</a>
					</li>
					<li class="nav-item" style="margin-left:20px;">
						<a href="/intelligence/interaction" class="active function_link" style="font-size: 25px;">文本引导</a>
					</li>
                    <li class="nav-item" style="margin-left:20px;">
                        <a href="/intelligence/image_generator" class="active function_link" style="font-size: 25px;">图片引导</a>
                    </li>
				</ul>
			</div>
		</div>

		<!-- 主内容 -->
		<div class="main_content">
			<div class="row" style="margin-top: 35px; margin-left: 200px;">
				<!-- 左侧 输入模块 -->
				<div class="col-md-6 offset-md-1">
					<div class="card">
						<div class="card-header" style="background: linear-gradient(to right, #43a047, #337ab7); color: #fff;">
							<h4 class="card-title">交互输入</h4>
						</div>
						<div class="card-body">
							<form id="sendForm">
								<div class="mb-3">
									<label for="event" class="form-label">输入事件主题</label>
									<textarea class="form-control" id="event" rows="3" placeholder="示例：新能源汽车发生火灾"
										style="resize: none;">AI普及引发部分岗位被替代</textarea>
								</div>
								<div class="mb-3">
									<label for="guideline" class="form-label">输入引导方向</label>
									<textarea class="form-control" id="guideline" rows="3"
										placeholder="示例：引导用户理性看待新能源技术发展的阶段性问题" style="resize: none;">引导用户关注人机协同与新技能培养</textarea>
								</div>
								<div class="mb-3">
									<label for="misconception" class="form-label">输入用户观点</label>
									<textarea class="form-control" id="misconception" rows="3"
										placeholder="示例：新能源车根本不安全，应该全面禁用" style="resize: none;">AI迟早让所有人失业，我们根本不该发展它</textarea>
								</div>
							</form>
							<button type="button" class="btn btn-primary col-md-2 offset-md-10 " id="sendButton" disabled style="margin-top: 20px;">
								<span class="spinner-border spinner-border-sm me-2 d-none" id="loadingSpinner"></span>
								<span id="btnText">发送</span>
							</button>
						</div>
					</div>
					<br>
					<div class="card" style="height: 500px;" id="resultPanel">
						<div class="card-header">
								<h4 class="card-title">输出的引导图片</h4>
						</div>
						<div class="card-body" id="resultPanelBody" style="overflow-y: auto; max-height: 450px;">
							<div class="image-placeholder" id="imagePlaceholder">
								<p style="color: #999;">生成的引导图片将显示在这里</p>
							</div>
						</div>
					</div>
				</div>

				<!-- 右侧 模型信息+按钮 -->
				<div class="col-md-3 offset-md-1">
					<div class="card">
						<div class="card-header">
							<h4 class="card-title">模型信息</h4>
						</div>
						<div class="card-body">
							<p><strong>模型名称：</strong> 智能文生图模型V1.0</p>
							<p><strong>响应时间：</strong> <span id="responseTime">-- ms</span></p>
						</div>
					</div>
					<br>
					<div class="card sample-card">
						<div class="card-body text-center">
							<h5 style="text-align: left;"><strong>样例主题：新能源汽车引发火灾</strong></h5>
							<h6 style="text-align: left;">引导方向：引导用户理解火灾可能涉及多个因素</h6>
							<h6 style="text-align: left;">用户观点：新能源车根本不安全，应该全面禁用</h6>
							<!-- <img src="{% static 't2i-images/2.png' %}"
								class="sample-image-preview" alt="样例图片预览"> -->
							<button class="btn btn-primary" onclick="fillExample(1)">点击使用样例</button>
						</div>
					</div>
					<br>
					<div class="card sample-card">
						<div class="card-body text-center">
							<h5 style="text-align: left;"><strong>样例主题：某网红直播带货虚假宣传引发舆论</strong></h5>
							<h6 style="text-align: left;">引导方向：引导用户理性区分个别主播与整个行业</h6>
							<h6 style="text-align: left;">用户观点：直播带货都是骗人的，应该全部取缔！</h6>
							<!-- <img src="{% static 't2i-images/1.png' %}"
								class="sample-image-preview" alt="样例图片预览"> -->
							<button class="btn btn-primary" onclick="fillExample(2)">点击使用样例</button>
						</div>
					</div>
					<br>
					<div class="card sample-card">
						<div class="card-body text-center">
							<h5 style="text-align: left;"><strong>样例主题：AI普及引发部分岗位被替代</strong></h5>
							<h6 style="text-align: left;">引导方向：引导用户关注人机协同与新技能培养</h6>
							<h6 style="text-align: left;">用户观点：AI迟早让所有人失业，我们根本不该发展它</h6>
							<!-- <img src="{% static 't2i-images/3.png' %}"
								class="sample-image-preview" alt="样例图片预览"> -->
							<button class="btn btn-primary" onclick="fillExample(3)">点击使用样例</button>
						</div>
					</div>


				</div>
			</div>

			<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
				<div class="modal-dialog modal-dialog-centered modal-lg">
					<div class="modal-content">
					<div class="modal-body text-center">
						<img id="modalImage" src="" class="img-fluid" alt="预览图片">
					</div>
					<div class="modal-footer">
						<a id="downloadLink" href="#" download class="btn btn-success">下载图片</a>
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
					</div>
					</div>
				</div>
			</div>

			<!-- 输出结果 -->
			<div class="results-container" style="margin-left: 100px;">
					<h4 style="margin-bottom: 20px; color: #333;">交互输出</h4>
					<table class="table table-striped table-bordered results-table">
						<thead>
							<tr>
								<th>时间</th>
								<th>事件</th>
								<th>引导方向</th>
								<th>用户观点</th>
								<th>输出图片</th>
							</tr>
						</thead>
						<tbody id="resultsTableBody">
						</tbody>
					</table>
				</div>
			</div>
		</div>

		<!-- 引入Bootstrap JavaScript -->
		<script src="{% static 'js/jquery.js' %}"></script>
		<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
		<script>
			//样例池
			const examples = {
			1: {
				event: "新能源汽车引发火灾",
				guideline: "引导用户理解火灾可能涉及多个因素，不应武断否定新能源车的发展",
				misconception: "新能源汽车经常自燃，说明这项技术根本不成熟，应该全部禁售",
                expectedImage: "{% static 't2i-images/2.png' %}"
			},
			2: {
				event: "某网红直播带货虚假宣传引发舆论",
				guideline: "引导用户理性区分个别主播与整个行业",
				misconception: "直播带货都是骗人的，应该全部取缔！",
                expectedImage: "{% static 't2i-images/1.png' %}"
			},
			3: {
				event: "AI普及引发部分岗位被替代",
				guideline: "引导用户关注人机协同与新技能培养",
				misconception: "AI迟早让所有人失业，我们根本不该发展它",
                expectedImage: "{% static 't2i-images/3.png' %}"
			}
			};

			// 一键填充函数
			function fillExample(no) {
			const data = examples[no];
			document.getElementById("event").value         = data.event;
			document.getElementById("guideline").value     = data.guideline;
			document.getElementById("misconception").value = data.misconception;

			// 触发输入事件，让“发送”按钮状态自动刷新
			["event", "guideline", "misconception"].forEach(id => {
				document.getElementById(id).dispatchEvent(new Event("input"));
			});
			
			// 手动更新按钮状态
			updateSendButtonState();
			}

			document.addEventListener("DOMContentLoaded", () => {
				const event = document.getElementById("event");
				const guideline = document.getElementById("guideline");
				const misconception = document.getElementById("misconception");
				const sendButton = document.getElementById("sendButton");
				const refreshButton = document.getElementById("refreshButton");
				const responseTimeElement = document.getElementById("responseTime");
				const resultsTableBody = document.getElementById("resultsTableBody");
				const resultPanel = document.getElementById("resultPanel");
				const resultPanelBody = document.getElementById("resultPanelBody");

				// 更新按钮启用状态
				function updateSendButtonState() {
					const hasContent =
						event.value.trim() !== "" &&
						guideline.value.trim() !== "" &&
						misconception.value.trim() !== "";
					sendButton.disabled = !hasContent;
				}
				[event, guideline, misconception].forEach((el) =>
					el.addEventListener("input", updateSendButtonState)
				);

				// 从JSON文件加载图片历史记录
				async function loadHistory() {
					try {
						const response = await axios.get("{% url 'get_image_results_from_json' %}");
						if (response.status == 200) {
							const historyData = response.data.results || [];

							// 先清空表格，防止重复显示
							const resultsTableBody = document.getElementById("resultsTableBody");
							resultsTableBody.innerHTML = '';

							// 调用渲染函数
							renderHistory(historyData);
						} else {
							console.error("后端返回失败信息:", response.data.error);
						}
					} catch (error) {
						console.error("加载历史记录失败:", error);
					}
				}

				// 渲染图片历史记录到表格
				function renderHistory(historyList) {
					console.log("renderHistory 接收到的数据:", historyList); // 添加调试信息
					const resultsTableBody = document.getElementById("resultsTableBody");
					historyList.forEach(item => {
						console.log("处理单个历史记录:", item); // 添加调试信息
						const tr = document.createElement("tr");

						const tdTime = document.createElement("td");
						tdTime.textContent = item.timestamp || '-';
						tr.appendChild(tdTime);

						const tdEvent = document.createElement("td");
						tdEvent.textContent = item.request?.event || '-';
						tr.appendChild(tdEvent);

						const tdGuideline = document.createElement("td");
						tdGuideline.textContent = item.request?.guideline || '-';
						tr.appendChild(tdGuideline);

						const tdInput = document.createElement("td");
						tdInput.textContent = item.request?.misconception || '-';
						tr.appendChild(tdInput);

						const tdOutput = document.createElement("td");
						console.log("检查图片数据:", item.image_data); // 添加调试信息
						// 检查是否有图片数据
						if (item.image_data?.image) {
							// 显示图片
							const img = document.createElement('img');
							// 构建完整的图片URL
							const imagePath = item.image_data.image;
							console.log("原始图片路径:", imagePath); // 添加调试信息
							
							// 如果是相对路径，需要转换为静态文件URL
							if (imagePath.startsWith('./')) {
								const staticPath = `/static/t2i-images/${imagePath.replace('./t2i-images/', '')}`;
								console.log("转换后的静态路径:", staticPath); // 添加调试信息
								img.src = staticPath;
							} else {
								img.src = imagePath;
							}
							img.className = "generated-image";
							img.style.maxWidth = "150px";  // 增加图片最大宽度
							img.style.maxHeight = "150px"; // 增加图片最大高度
							img.style.borderRadius = "6px"; // 增加圆角
							img.style.boxShadow = "0 3px 8px rgba(0,0,0,0.15)"; // 增强阴影
							img.style.display = "block"; // 确保图片居中显示
							img.style.margin = "0 auto"; // 图片居中
							img.alt = "历史图片";
							img.addEventListener('click', () => {
							document.getElementById('modalImage').src = img.src;
							document.getElementById('downloadLink').href = img.src;
							const modalElement = document.getElementById('imageModal');
							const modal = new bootstrap.Modal(modalElement);
							modal.show();
						});
							tdOutput.appendChild(img);
							tdOutput.classList.add("result-success");
						} else {
							tdOutput.textContent = '无图片';
							tdOutput.classList.add("result-failure");
						}
						tr.appendChild(tdOutput);

						resultsTableBody.appendChild(tr);
					});
				}


                // 修改显示结果函数
                function showRecentResult(result) {
                    console.log("showRecentResult 接收到的参数:", result);
                    // 清空之前的内容
                    resultPanelBody.innerHTML = "";

                    // 创建图片容器
                    const imageContainer = document.createElement("div");
                    imageContainer.className = "image-result-container";

                    if (result.success && result.image) {
                        // 成功获取图片
                        const img = document.createElement("img");
                        img.src = `data:image/png;base64,${result.image}`;
                        img.alt = "引导图片";
                        img.className = "generated-image";
                        img.style.maxWidth = "300px";
                        img.style.maxHeight = "300px";

						img.addEventListener('click', () => {
							document.getElementById('modalImage').src = `data:image/png;base64,${result.image}`;
							document.getElementById('downloadLink').href = `data:image/png;base64,${result.image}`;
							const modalElement = document.getElementById('imageModal');
							const modal = new bootstrap.Modal(modalElement);
							modal.show();
						});

                        const caption = document.createElement("p");
                        if (result.image_source === "local") {
                            caption.textContent = "从本地文件获取的图片";
                            caption.style.color = "#28a745"; // 绿色表示本地图片
                        } else if (result.is_fallback) {
                            caption.textContent = "示例图片（真实图片生成失败）";
                            caption.style.color = "#ff6b35"; // 橙色表示示例图片
                        } else {
                            caption.textContent = "大模型生成的图片";
                            caption.style.color = "#007bff"; // 蓝色表示生成的图片
                        }
                        caption.style.marginTop = "10px";

                        // 如果有提示词，显示提示词
                        if (result.text) {
                            const promptDiv = document.createElement("div");
                            promptDiv.innerHTML = `<strong>引导文本:</strong> ${result.text}`;
                            promptDiv.style.marginTop = "10px";
                            promptDiv.style.padding = "10px";
                            promptDiv.style.backgroundColor = "#f8f9fa";
                            promptDiv.style.borderRadius = "5px";
                            promptDiv.style.fontSize = "14px";
                            imageContainer.appendChild(promptDiv);
                        }

                        // 如果是示例图片，显示警告信息
                        if (result.is_fallback) {
                            const warningDiv = document.createElement("div");
                            warningDiv.className = "alert alert-warning";
                            warningDiv.innerHTML = `<strong>注意:</strong> 真实图片生成服务不可用，显示的是示例图片。请检查图片生成服务是否正常运行。`;
                            warningDiv.style.marginTop = "10px";
                            imageContainer.appendChild(warningDiv);
                        }

                        imageContainer.appendChild(img);
                        // imageContainer.appendChild(caption);
                    } else {
                        // 显示错误信息
                        const errorMsg = document.createElement("div");
                        errorMsg.className = "alert alert-danger";
                        errorMsg.textContent = result.error || "图片获取失败";
                        imageContainer.appendChild(errorMsg);
                    }

                    resultPanelBody.appendChild(imageContainer);
                    resultPanel.style.display = "block";
                }

				sendButton.addEventListener("click", async () => {
					const title = event.value.trim() || "-";
					const direction = guideline.value.trim() || "-";
					const text = misconception.value.trim();
					const spinner = document.getElementById('loadingSpinner');
					const btnText = document.getElementById('btnText');

					resultPanelBody.innerHTML = "<div class=\"image-placeholder\" id=\"imagePlaceholder\"><p style=\"color: #999;\">生成的引导图片将显示在这里</p></div>";

					if (!text) {
						alert("请输入用户观点！");
						return;
					}

					// 记录开始时间
					const sendTime = Date.now();

					// 禁用发送按钮，防止重复提交
					sendButton.disabled = true;
					spinner.classList.remove('d-none');
    				btnText.textContent= "生成中...";

					//发送数据
					const formData = new FormData();
					formData.append("event", title);
					formData.append("guideline", direction);
					formData.append("misconception", text);

					try {
						const response = await axios.post("{% url 'generate_image_from_text' %}", formData, {
							headers: {
								"X-CSRFToken": "{{ csrf_token }}",
								"Content-Type": "multipart/form-data"
							}
						});

						const result = response.data;
						const responseTime = result.response_time || (Date.now() - sendTime);
						responseTimeElement.textContent = `${responseTime} ms`;

						// 显示最近交互结果
						showRecentResult({
							event: title,
							guideline: direction,
							misconception: text,
							success: result.success,
							image: result.image,
							text: result.text,
							is_fallback: result.is_fallback,
							image_source: result.image_source,
							error: result.error,
							response_time: responseTime
						});

						// // 构建新行
						// const tr = document.createElement("tr");

						// //时间
						// const tdTime = document.createElement("td");
						// tdTime.textContent = result.timestamp || new Date().toLocaleString();
						// tr.appendChild(tdTime);

						// //事件
						// const tdEvent = document.createElement("td");
						// tdEvent.textContent = title;
						// tr.appendChild(tdEvent);

						// //方向
						// const tdGuideline = document.createElement("td");
						// tdGuideline.textContent = direction;
						// tr.appendChild(tdGuideline);

						// //输入内容
						// const tdInput = document.createElement("td");
						// tdInput.textContent = text;
						// tr.appendChild(tdInput);

						// //输出内容
						// const tdOutput = document.createElement("td");
						// tdOutput.id = "output";

						// console.log("表格输出结果:", result); // 添加调试信息
						// if (result.success) {
						// 	tdOutput.classList.add("result-success");
						// 	// 只显示图片，不显示其他信息
						// 	if (result.image) {
						// 		const img = document.createElement('img');
						// 		img.src = `data:image/png;base64,${result.image}`;
						// 		img.className = "generated-image";
						// 		img.style.maxWidth = "150px";  // 增加图片最大宽度
						// 		img.style.maxHeight = "150px"; // 增加图片最大高度
						// 		img.style.borderRadius = "6px"; // 增加圆角
						// 		img.style.boxShadow = "0 3px 8px rgba(0,0,0,0.15)"; // 增强阴影
						// 		img.style.display = "block"; // 确保图片居中显示
						// 		img.style.margin = "0 auto"; // 图片居中
						// 		tdOutput.appendChild(img);
						// 	} else {
						// 		tdOutput.textContent = "无图片";
						// 	}
						// } else {
						// 	tdOutput.classList.add("result-failure");
						// 	tdOutput.textContent = `图片获取失败: ${result.error || '未知错误'}`;
						// }

						// tr.appendChild(tdOutput);
						// resultsTableBody.appendChild(tr);
						// tr.scrollIntoView({
						// 	behavior: "smooth",
						// 	block: "end"
						// });

						// 发送后自动刷新历史记录
						loadHistory();
					} catch (error) {
						console.error("请求失败:", error);

						// 显示错误结果
						showRecentResult({
							event: title,
							guideline: direction,
							misconception: text,
							success: false,
							error: `服务器异常: ${error.message}`,
							response_time: Date.now() - sendTime
						});

						// 构建错误行
						const tr = document.createElement("tr");

						const tdTime = document.createElement("td");
						tdTime.textContent = new Date().toLocaleString();
						tr.appendChild(tdTime);

						const tdEvent = document.createElement("td");
						tdEvent.textContent = title;
						tr.appendChild(tdEvent);

						const tdGuideline = document.createElement("td");
						tdGuideline.textContent = direction;
						tr.appendChild(tdGuideline);

						const tdInput = document.createElement("td");
						tdInput.textContent = text;
						tr.appendChild(tdInput);

						const tdOutput = document.createElement("td");
						tdOutput.id = "output";
						tdOutput.classList.add("result-failure");
						tdOutput.textContent = `服务器异常：${error.message}`;
						tr.appendChild(tdOutput);

						resultsTableBody.appendChild(tr);
					}

					// 重新启用发送按钮
					spinner.classList.add('d-none');
					btnText.textContent = "发送";
					sendButton.disabled = false;
				});

				// 绑定发送与enter键
				document.addEventListener('keydown', function (e) {
				// 如果按的是 Enter 且发送按钮不是禁用状态，就触发点击
				if (e.key === 'Enter' && !document.getElementById('sendButton').disabled) {
					e.preventDefault();          // 阻止默认行为（如换行）
					document.getElementById('sendButton').click();
				}
				});

				// 初始化
				updateSendButtonState(); // 页面加载时初始化按钮状态
				loadHistory(); // 加载历史记录
			});
		</script>
	</body>
</html>